import dayjs, { WEEKDAY } from '@/plugins/dayjs'
import { t } from 'i18next'
/*
getUrlParams 
获得地址栏参数
*/
export function getUrlParams(param = 'meetingMoid') {
	var reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)')
	var r = window.location.search.substring(1).match(reg)
	if (r != null) return decodeURI(r[2])
	return undefined
}

export function isMeetingCore() {
	return import.meta.env.DEV
		? import.meta.env.VITE_API_USE_CORE === '0'
			? false
			: ['/manager.html', '/sign_result.html', '/meetingSpace.html'].includes(window.location.pathname)
			? false
			: true
		: window.location.pathname.startsWith('/meetingCore')
}

export function filterMtName(mt: any) {
	let obj = { ...mt }
	if (
		obj.stream &&
		obj.stream != undefined &&
		obj.stream == 1 &&
		obj.name.indexOf(t('[多流]')) == -1 &&
		obj.online == 1
	) {
		obj.name = t('[多流]') + obj.name
	}
	return obj
}

export const Environment = {
	isMobile:
		/Android|webOS|iPhone|iPod|BlackBerry|iPad/i.test(window.navigator.userAgent) ||
		(window.navigator.platform === 'MacIntel' && window.navigator.maxTouchPoints > 1),
	isAndroid:
		window.navigator.userAgent.toLowerCase().indexOf('android') > -1 ||
		window.navigator.userAgent.toLowerCase().indexOf('adr') > -1,
	isIOS:
		!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) || window.navigator.platform === 'MacIntel',
	isInWeiXin:
		window.navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1 ||
		window.location.href.toLocaleLowerCase().indexOf('wx') > -1 ||
		window.navigator.userAgent.toLowerCase().indexOf('wxwork') > -1,

	isWeiXinWork: window.navigator.userAgent.toLowerCase().indexOf('wxwork') > -1,

	isMac: /macintosh|mac os x/i.test(window.navigator.userAgent),

	isIE: /(msie\s|trident.*rv:)([\w.]+)/i.test(window.navigator.userAgent.toLowerCase()),
}
export const regexEnum = {
	account: '^[\u4e00-\u9fa5\\w\\.@]+$', // 中文、英文字母（大小写）、数字、“_”、“@”、“.”
	email: '^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$', // 英文字母（大小写）、数字、“_”、“@”、“.” ,"-"
	name: '^[\u4e00-\u9fa5\\w]+$', // 中文、英文字母（大小写）、数字、“_“
	mobile: '^\\d{11}$', // 数字。
	extNum: '^[0-9（）()\\-，,；;*+#. ]{1,30}$', // 分机只允许输入"数字、（、）、，、-、；、*、+、#、空格、."！
	networkDomain: '^[0-9a-zA-Z.\\-]{1,128}$', // 英文（大小写不敏感）、数字、“.”、“-”;
	fax: '^[0-9-]{1,32}$', // 数字、“-”
	/**预案用 */
	testLength: /^.{0,16}$/,
	testCharacter: /^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[A-Za-z0-9. ])*$/,
	testSpecial: /^((?!\<|\>|"|'|\\|\/).)*$/,
	//非法字符
	videoNameIllegal: /^[\u4e00-\u9fa5A-Za-z0-9\-\.\_\s\@\#\(\)\（\）]+$/,
	nameIllegal: /^[\u4e00-\u9fa5A-Za-z0-9\-\.\_\s\@\#\(\)\（\）]+$/,
	phoneIllegal: /^[0-9\.\_\-\*\#\s]+$/,
	phoneMaxLength: /^.{0,20}$/,
}
export const Rules = {
	checkIsIP6: (value: string) => {
		var reg1 = /^[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}$/
		var reg2 = /^(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)::(([0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4}){0,5})?)$/
		var check = reg1.test(value) || reg2.test(value)
		return check
	},
}
/** 拖蓝效果 */
export function createRange(element: HTMLElement | null): void {
	if (!element) {
		return
	}
	const selection = window.getSelection()
	const range = document.createRange()
	range.selectNodeContents(element)

	selection?.removeAllRanges()
	selection?.addRange(range)
}

export function checkPermission(userPermissions: string, permission: string) {
	//ie 不兼容直接 0bxxx
	return (Number('0b' + userPermissions) & Number('0b' + permission)) === Number('0b' + userPermissions)
}

export const getCheckPreNameRule = (characterLimit: 0 | 1) => {
	return characterLimit
		? [
				{
					regex: regexEnum.testCharacter,
					msg: t('预案名称输入错误'),
				},
				{
					regex: regexEnum.testSpecial,
					msg: t('预案名称不能包含敏感字符'),
				},
				{
					regex: regexEnum.testLength,
					msg: t('预案名称最多16个字符'),
				},
		  ]
		: [
				{
					regex: regexEnum.testLength,
					msg: t('预案名称最多16个字符'),
				},
		  ]
}

export const getMeetingTime = (startTime: string, duration: number, permanent: boolean) => {
	let hour = Math.floor(duration / 60)
	let minute = duration % 60
	let day = dayjs(startTime).format('YYYY-MM-DD')
	let time = dayjs(startTime).format('HH:mm')
	let weekDay = WEEKDAY[dayjs(startTime).weekday()]
	let dateTime = t('{{day}} {{weekDay}} {{startTime}}开始，', {
		day: day,
		weekDay: weekDay,
		startTime: time,
	})
	if (permanent) {
		//永久会议
		dateTime += t('手动结束')
	} else {
		if (minute !== 0 && hour !== 0) {
			dateTime += t('时长{{hour}}小时{{minute}}分钟', { hour: hour, minute: minute })
		} else if (hour !== 0) {
			dateTime += t('时长{{hour}}小时', { hour: hour })
		} else if (minute !== 0) {
			dateTime += t('时长{{minute}}分钟', { minute: minute })
		}
	}
	return dateTime
}

export const getRegularMeetingTime = (
	start_time: string,
	duration: number,
	meeting_formular: { week_days: string; start_date: string; end_date: string }
) => {
	const weekDayLabels = meeting_formular?.week_days
		? meeting_formular?.week_days
				.split(',')
				.map((item) => WEEKDAY[Number(item)])
				.join('、')
		: ''
	const startDate = meeting_formular?.start_date ? dayjs(meeting_formular.start_date).format('YYYY-MM-DD') : ''
	const endDate = meeting_formular?.end_date ? dayjs(meeting_formular.end_date).format('YYYY-MM-DD') : ''
	const startTime = dayjs(start_time).format('HH:mm') //会议开始时间
	const hour = Math.floor(duration / 60)
	const minute = duration % 60
	let dateTime =
		t('{{startDate}}开始，到{{endDate}}结束 ', {
			startDate: startDate,
			endDate: endDate,
		}) +
		' ' +
		t('每周的{{weekDayLabels}} {{startTime}}开始，', {
			weekDayLabels: weekDayLabels,
			startTime: startTime,
		})
	if (minute !== 0 && hour !== 0) {
		dateTime += t('时长{{hour}}小时{{minute}}分钟', {
			hour: hour,
			minute: minute,
			weekDayLabels: weekDayLabels,
			startTime: startTime,
		})
	} else if (hour !== 0) {
		dateTime += t('时长{{hour}}小时', { hour: hour })
	} else if (minute !== 0) {
		dateTime += t('时长{{minute}}分钟', { minute: minute })
	}
	return dateTime
}

export function getUTF8ByteCount(char: string) {
	// 将字符转换为UTF-8编码的字节序列
	const encodedChar = unescape(encodeURIComponent(char))
	// 获取字节数
	const byteCount = encodedChar.length
	return byteCount
}

export const getScrollbarSize = (recalc?: boolean): number | undefined => {
	let size = undefined
	if (size === undefined || recalc) {
		if (!!(typeof window !== 'undefined' && window.document && window.document.createElement)) {
			const scrollDiv = document.createElement('div')
			const body: any = document.body

			scrollDiv.style.position = 'absolute'
			scrollDiv.style.top = '-9999px'
			scrollDiv.style.width = '50px'
			scrollDiv.style.height = '50px'
			scrollDiv.style.overflow = 'scroll'

			body.appendChild(scrollDiv)
			size = scrollDiv.offsetWidth - scrollDiv.clientWidth
			body.removeChild(scrollDiv)
		}
	}

	return size
}

export const saveAs = (downfile: Blob, name: string) => {
	const tmpLink = document.createElement('a')
	const objectUrl = URL.createObjectURL(downfile)
	tmpLink.href = objectUrl
	tmpLink.download = name
	document.body.appendChild(tmpLink)
	tmpLink.click()
	document.body.removeChild(tmpLink)
	URL.revokeObjectURL(objectUrl)
}
